var data = [];


var FormEX = require(path.join(__dirname, 'form.js'));
var interface = require(path.join(__dirname, '_list.js')).interface;
var dialogEX = Require('./component/_dialog.js');
var dialog = require('electron').remote.dialog;
var inputEX = FormEX.input;
var textareaEX = FormEX.textarea;
var compressFile = Require('./component/getBase64.js');
var saveFile = Require('./component/saveFile.js');
var formatDate = Require('./component/formatDate.js');




var answerBox = function (data) {
    this.html = $('<div class="answerBox list custom-scroll theme-scroll list"></div>');
    this.empty = $('<div class="empty">没有内容</div>');
    this.box = $('<div></div>');
    this.item = {};
    this.box.append(this.empty);
    this.html.append(this.box);
    this.set(data);
};
answerBox.prototype.render = function () {
    return this.html;
};
answerBox.prototype.append = function (data) {
    if (this.item.hasOwnProperty(data.id)) {
        this.active(data.id, () => {
            this.item[data.id].html.addClass('interface_flicker');
            setTimeout(() => {
                this.item[data.id].html.removeClass('interface_flicker');
            }, 500);
        });
    } else {
        this.item[data.id] = new interface(data, this);
        var deleteButton = $('<i class="fa fa-trash-o"></i>').click((e) => {
            event.stopPropagation();
            this.remove(data.id);
        });
        this.box.append(this.item[data.id].render());
        this.item[data.id].title.append(deleteButton);
        this.active(data.id, () => { });
        if (this.empty) {
            this.empty.remove();
            this.empty = null;
        };
    };
};
answerBox.prototype.remove = function (id) {
    if (this.item.hasOwnProperty(id)) {
        dialogEX({
            title: '警告',
            body: '<div style="padding:20px;">是否删除关联?</div>',
            buttons: [{
                text: '是',
                event: (dialogEvent) => {
                    this.item[id].html.remove();
                    delete this.item[id];
                    dialogEvent.close();
                },
            }, {
                text: '否',
                event: (dialogEvent) => {
                    dialogEvent.close();
                },
            }],
            width: 400,
            height: 200
        });
    };
};
answerBox.prototype.active = function (id, cb) {
    var moveObj = () => {
        var obj = this.item[id].html;
        var Min = this.html.offset().top;
        var Max = Min + 300;
        var top = obj.offset().top;
        var height = 23;
        if (top < Min) {
            this.html.scrollTop(this.html.scrollTop() - 10);
            setTimeout(() => {
                moveObj();
            }, 5)
        } else if (top > Max - height) {
            this.html.scrollTop(this.html.scrollTop() + 10);
            setTimeout(() => {
                moveObj();
            }, 5)
        } else {
            cb();
        }
    };
    moveObj();
};
answerBox.prototype.get = function () {
    var data = [];
    for (const key in this.item) {
        if (this.item.hasOwnProperty(key)) {
            const element = this.item[key];
            data.push(element.config.id);
        }
    };
    return data;
};
answerBox.prototype.set = function (data) {
    this.box.empty();
    console.log(data);
    __DBObject__.list.GetByArray(data, (error, docs) => {
        for (let i = 0; i < docs.length; i++) {
            const element = docs[i];
            this.append(element);
        };
    });
};



var imgItem = function (data, parent, unDelete) {
    this.parent = parent;
    this.data = data;
    this.html = $('<div class="img_item"></div>');
    var text = $('<div class="img_item_text">' + data.title + '</div>');
    if (!unDelete) {
        var _delete = $('<div class="fa delete fa-trash-o" title="删除"></div>');
        _delete.click(() => {
            this.delete();
        });
    };
    this.html.append(text).append(_delete);
    text.click(() => {
        this.lookimg();
    });
};
imgItem.prototype.render = function () {
    return this.html;
};
imgItem.prototype.preview = function (title, base64) {
    dialogEX({
        title: title,
        body: '<div style="padding:20px"><img src="' + base64 + '" style="width:100%" /></div>',
        buttons: [{
            text: '保存到本地',
            event: (dialogEvent) => {
                dialog.showSaveDialog({
                    title: '保存图片',
                    defaultPath: title,
                    filters: [
                        { name: 'jpg', extensions: ['jpg'] },
                        { name: 'png', extensions: ['png'] }
                    ],
                }, function (filenames) {
                    if (filenames) {
                        saveFile(filenames, base64);
                    };
                })
            },
        }],
    });
};
imgItem.prototype.lookimg = function () {
    if (this.data.id) {
        __DBObject__.Image.get(this.data.id, (error, doc) => {
            if (error) {
                alert(error);
            } else {
                this.preview(this.data.title, doc.base64);
            }
        });
    } else {
        this.preview(this.data.title, this.data.data);
    };
};
imgItem.prototype.delete = function () {
    dialogEX({
        title: '警告',
        body: '<div style="padding:20px;">是否删除图片?</div>',
        buttons: [{
            text: '是',
            event: (dialogEvent) => {
                this.html.remove();
                if (this.data.id) {
                    this.parent.removeShowItem(this);
                } else {
                    this.parent.removeCreatItem(this);
                };
                dialogEvent.close();
            },
        }, {
            text: '否',
            event: (dialogEvent) => {
                dialogEvent.close();
            },
        }],
        width: 400,
        height: 200
    });
};


var imageShowList = function (data) {
    this.data = data;
    this.html = $('<div class="imageList"></div>');
    this.title = $('<div class="imageList_title">图片列表</div>');
    this.box = $('<div></div>');
    this.html.append(this.title).append(this.box);
    this.set(data);
};
imageShowList.prototype.render = function () {
    return this.html;
};
imageShowList.prototype.set = function (data) {
    this.box.empty();
    for (let i = 0; i < data.length; i++) {
        const element = data[i];
        this.box.append(new imgItem(element, this, true).render());
    };
};



var imageList = function (data) {
    this.data = data;
    this.html = $('<div class="imageList"></div>');
    this.title = $('<div class="imageList_title">图片列表</div>');
    this.addButton = $('<div class="addButton"><i class="fa fa-plus-circle"></i>添加图片</div>');
    this.html.append(this.title.append(this.addButton));
    this.addButton.click(() => {
        this.readFile();
    });
    this.showList = [];
    this.creatList = [];
    this.deleteList = [];
    for (let i = 0; i < data.length; i++) {
        const element = data[i];
        this.addItem(element);
    };
};
imageList.prototype.render = function () {
    return this.html;
};
imageList.prototype.readFile = function () {
    var input = inputEX({
        size: 'normal',
        jude: {
            name: '标题',
            rules: ['notNull']
        },
        readonly: false,
        placeholder: '标题',
    });
    var html = $('<div class="note_readFile"></div>');
    var button = $('<div class="btn" style="margin:0">选择文件</div>');
    var base64 = null;
    button.click(() => {
        dialog.showOpenDialog({
            title: '选择图片',
            filters: [
                { name: '图片', extensions: ['jpg', 'png'] },
            ],
            properties: ['openFile', 'createDirectory'],
        }, function (filenames) {
            if (filenames) {
                var file = filenames[0];
                var pos = file.lastIndexOf("\\");
                var name = file.substring(pos + 1);
                compressFile(file, function (error, data) {
                    if (error) {
                        alert(error);
                    } else {
                        base64 = data;
                        input.set(name);
                    };
                });
            };
        });
    });
    html.append(input.render()).append('<div style="clear:both"></div>').append(button);
    dialogEX({
        title: '上传图片',
        body: html,
        buttons: [{
            text: '确定',
            event: (dialogEvent) => {
                input.get((error, doc) => {
                    if (error) {
                        alert(error);
                    } else {
                        this.addItem({
                            data: base64,
                            title: doc
                        });
                    }
                    dialogEvent.close();
                });
            },
        }],
        width: 400,
        height: 205
    });
};
imageList.prototype.addItem = function (data) {
    var item = new imgItem(data, this);
    if (!data.id) {
        this.creatList.push(item);
    };
    this.html.append(item.render());
};
imageList.prototype.removeCreatItem = function (data) {
    for (let i = 0; i < this.creatList.length; i++) {
        const element = this.creatList[i];
        if (element === data) {
            this.creatList.splice(i, 1);
            break;
        };
    }
};
imageList.prototype.removeShowItem = function (data) {
    this.deleteList.push(data.data.id);
};
imageList.prototype.get = function () {
    var creatData = [];
    for (let i = 0; i < this.creatList.length; i++) {
        const element = this.creatList[i];
        creatData.push(element.data);
    };
    var data = {
        deleteImg: this.deleteList,
        creatImg: creatData
    };
    return data;
};


var editorBox = function (data, parent) {
    this.html = $('<div class="editorBox"></div>');
    this.input = inputEX({
        size: 'block',
        jude: {
            name: '标题',
            rules: ['notNull']
        },
        readonly: false,
        placeholder: '标题',
    });
    this.textarea = textareaEX({
        size: 'block',
        jude: {
            name: '备注',
            rules: []
        },
        readonly: false,
        placeholder: '备注',
    });
    this.input.set(data.title);
    this.textarea.set(data.description);
    this.confirm = $('<div class="confirm button">确定</div>');
    this.cancel = $('<div class="cancel button">取消</div>');
    this.cf = $('<div class="cf"></div>');
    this.cancel.click(() => {
        parent.editorHide(false);
    });
    this.confirm.click(() => {
        this.get((data) => {
            parent.editorHide(data);
        });
    });
    this.searchBox = $('<div class="searchBox"></div>');
    this.search = Require('./component/_search.js')();
    this.searchBox.append(this.search.render());
    this.search.on('renderList', function (event, data, contentType) {
        event.loading();
        __DBObject__.list.search(data, contentType, function (error, docs) {
            event.setData(docs);
            if (docs.length == 0) {
                event.showMark();
            };
            event.loading();
        });
    });
    this.answerBox = new answerBox(data.interface);
    this.imageList = new imageList(data.images);
    this.pushToAnswerBox = $('<div class="pushToAnswerBox"><i class="fa fa-angle-right"></i></div>');
    this.pushToAnswerBox.find('i').click(() => {
        if (this.search.activeObj) {
            this.answerBox.append(this.search.activeObj.config);
        };
    });
    this.files = [];
    this.html.append(this.input.render()).append(this.textarea.render())
    this.html.append(this.searchBox);
    this.html.append(this.pushToAnswerBox);
    this.html.append(this.answerBox.render()).append('<div class="cf"></div>');
    this.html.append(this.imageList.render()).append('<div class="cf"></div>');
    this.html.append(this.confirm).append(this.cancel).append('<div class="cf"></div>');
};
editorBox.prototype.render = function () {
    return this.html;
};
editorBox.prototype.get = function (callBack) {
    this.input.get((error, inputDoc) => {
        if (error) {
            alert(error);
        } else {
            this.textarea.get((error, textareaDoc) => {
                if (error) {
                    alert(error);
                } else {
                    callBack({
                        title: inputDoc,
                        description: textareaDoc,
                        answerBox: this.answerBox.get(),
                        imageList: this.imageList.get()
                    });
                }
            });
        }
    });
};

var interfaceList = function (data, parent) {
    this.parent = parent;
    this.data = data;
    this.html = $('<div class="imageList list"></div>');
    this.title = $('<div class="imageList_title">接口</div>');
    this.box = $('<div></div>');
    this.html
        .append(this.title)
        .append(this.box);
    this.set(data);
};
interfaceList.prototype.render = function () {
    return this.html;
};
interfaceList.prototype.active = function () {

};
interfaceList.prototype.set = function (data) {
    this.box.empty();
    __DBObject__.list.GetByArray(data, (error, docs) => {
        for (let i = 0; i < docs.length; i++) {
            const element = new interface(docs[i], this, true);
            this.box.append(element.render());
            element.title.click(() => {
                console.log(docs[i], this.parent);
            });
        };
    });
};



var subItem = function (data, parent) {
    this.data = data;
    this.parent = parent;
    this.html = $('<div class="subItem"></div>');
    this.showBox = $('<div class="showBox"></div>');
    this.titleBox = $('<div class="title"></div>');
    this.title = $('<div class="titleText">' + data.title + '</div>');
    this.description = $('<div class="description">' + data.description + '</div>');
    this.editorButton = $('<div class="fa editor fa-edit" title="编辑"></div>');
    this.delete = $('<div class="fa delete fa-trash-o" title="删除"></div>');
    this.titleBox
        .append(this.title)
        .append(this.editorButton)
        .append(this.delete);
    this.html.append(this.showBox);
    this.editorButton.click(() => {
        this.editorShow();
    });
    this.showImageList = new imageShowList(data.images);
    this.interfaceList = new interfaceList(data.interface, this.parent);
    this.showBox
        .append(this.titleBox)
        .append(this.description)
        .append(this.interfaceList.render())
        .append(this.showImageList.render())
        .append('<div class="cf"></div>');
};
subItem.prototype.render = function () {
    return this.html;
};
subItem.prototype.editorShow = function () {
    this.showBox.css('display', 'none');
    this.editorBox = new editorBox(this.data, this);
    this.html.append(this.editorBox.render());
};
subItem.prototype.upDateImage = function (ans, cb) {
    __DBObject__.Image.creatByArray(ans.imageList.creatImg, function (error, doc) {
        if (error) {
            alert(error);
        } else {
            cb(doc);
        }
    });
};
subItem.prototype.editorHide = function (ans) {
    if (ans) {
        this.upDateImage(ans, (result) => {
            if (this.parent && (this.data.isNew || this.parent.data.isNew)) {
                if (this.parent.data.type == 'main') {
                    this.Creat({
                        type: 'main',
                        description: ans.description,
                        title: ans.title,
                        images: result,
                        interface: ans.answerBox,
                        time: this.parent.data.time,
                        isNew: false,
                        parentId: null,
                        subset: [],
                    }, (doc) => {
                        console.log(doc);
                        var _item = new item(doc, this.parent);
                        this.parent.html.after(_item.render());
                        this.parent.html.remove();
                    });
                } else {
                    var _item = new subItem({
                        type: 'subset',
                        id: 'xxx',
                        description: ans.description,
                        title: ans.title,
                        images: ans.imageList,
                        interface: ans.answerBox,
                        parentId: '',
                        isNew: false,
                    });
                    this.html.after(_item.render());
                    this.html.remove();
                }
            } else {
                this.set(ans);
                this.hide();
            };
        });
    } else {
        this.hide();
    };
};
subItem.prototype.Creat = function (data, cb) {
    __DBObject__.Content.creat(data, (error, doc) => {
        if (error) {
            alert(error);
        } else {
            cb(doc);
        }
    });
};


subItem.prototype.set = function (ans) {
    this.title.text(ans.title);
    this.showImageList.set(ans.imageList);
    this.interfaceList.set(ans.answerBox);
    this.description.text(ans.description);
};
subItem.prototype.hide = function () {
    this.editorBox.html.remove();
    this.editorBox = null;
    this.showBox.css('display', 'block');
    if (this.data.isNew) {
        this.html.remove();
    };
    if (this.parent && this.parent.data.isNew) {
        this.parent.remove();
    };
};


var subset = function (data, parent) {
    this.parent = parent;
    this.data = data;
    this.html = $('<div class="subset"></div>');
    this.subsetTitle = $('<div class="subset_title">需求分析 : </div>');
    this.changeButton = $('<div class="fa fa-angle-up changeButton"></div>');
    this.addButton = $('<div class="addButton"><i class="fa fa-plus-circle"></i>添加分析</div>');

    this.addButton.click(() => {
        var item = new subItem({
            title: '',
            description: '',
            type: 'subset',
            interface: [],
            images: [],
            isNew: true,
        }, this);
        this.box.prepend(item.render());
        item.editorShow();
    });

    // prepend

    this.html.append(this.subsetTitle);
    this.subsetTitle.append(this.changeButton).append(this.addButton);
    this.box = $('<div></div>')
    this.html.append(this.box);
    this.changeButton.click(() => {
        if (this.status) {
            this.hide();
        } else {
            this.show();
        }
    });
    for (let i = 0; i < data.length; i++) {
        const element = data[i];
        this.box.append(new subItem(element, this.parent).render());
    };
    this.status = false;
    this.hide();
};
subset.prototype.render = function () {
    return this.html;
};
subset.prototype.show = function () {
    this.status = true;
    this.addButton.css('display', 'block');
    this.changeButton.removeClass('fa-angle-down').addClass('fa-angle-up');
    this.box.css('display', 'block');
};
subset.prototype.hide = function () {
    this.status = false;
    this.addButton.css('display', 'none');
    this.changeButton.removeClass('fa-angle-up').addClass('fa-angle-down');
    this.box.css('display', 'none');
};

var item = function (data, parent) {
    this.parent = parent;
    this.data = data;
    this.html = $('<div class="noteItem"></div>');
    this.line = $('<div class="line"></div>');
    this.time = $('<div class="time">' + formatDate('YYYY年MM月DD日 HH时mm分ss秒', data.time) + '</div>');
    this.point = $('<div class="point"></div>');
    this.content = $('<div class="content"></div>');
    this.mainItem = new subItem({
        title: data.title,
        description: data.description,
        images: data.images,
        interface: data.interface,
    }, this);
    this.content.append(this.mainItem.render());
    if (!data.isNew) {
        this.content.append(new subset(data.subset, this).render());
    };
    this.html.append(this.line).append(this.time).append(this.point).append('<div style="height:1px;"></div>').append(this.content);
};
item.prototype.render = function () {
    return this.html;
};
item.prototype.remove = function () {
    this.html.remove();
};

var note = function () { };
note.prototype.render = function () {
    this.getList();
    return this.html;
};
note.prototype.show = function () {
    this.html.css({ display: 'block' });
};
note.prototype.hide = function () {
    this.html.css({ display: 'none' });
};
note.prototype.getList = function () {
    this.html = $('<div id="note"></div>');
    this.box = $('<div class="box"></div>');
    this.scroll = $('<div class="scroll"></div>');
    this.html.append(this.box).append(this.scroll);
    this.addButton = $('<div class="noteItem">\
                            <div class="line"></div>\
                            <div class="time">现在</div>\
                            <div class="point"></div>\
                            <div style="height:1px;"></div>\
                            <div class="content" style="width: 74px; font-size:14px; color:#666;">\
                                <i class="fa fa-plus-circle" style="color: #3399ff;margin:0 5px 0 0"></i>点击添加\
                            </div>\
                        </div>');
    this.box.append(this.addButton);
    this.addButton.find('.content').click(() => {
        var _item = new item({
            time: new Date().getTime(),
            title: '',
            description: '',
            type: 'main',
            interface: [],
            subsets: [],
            images: [],
            isNew: true,
            parentId: null,
        }, this);
        this.addButton.after(_item.render());
        _item.mainItem.editorShow();
    });
    __DBObject__.Content.getAllMain((error, docs) => {
        if (error) {
            alert(docs);
        } else {
            for (let i = 0; i < docs.length; i++) {
                const element = docs[i];
                this.box.append(new item(element).render());
            };
        }
    });
};



module.exports = function () {
    return new note();
};